package com.example.myapplicationthirteen.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广播管理工具类
 * 遵循最佳实践："能用地播不用全局，能动态注册不用静态"
 */
public class BroadcastManager {
    private static final String TAG = "BroadcastManager";
    private final Context context;
    private final LocalBroadcastManager localBroadcastManager;
    private final Map<BroadcastReceiver, RegisteredReceiverInfo> registeredReceivers;

    public BroadcastManager(Context context) {
        this.context = context.getApplicationContext(); // 使用Application Context避免内存泄漏
        this.localBroadcastManager = LocalBroadcastManager.getInstance(this.context);
        this.registeredReceivers = new HashMap<>();
    }

    /**
     * 发送普通全局广播
     */
    public void sendNormalBroadcast(String action, String data) {
        sendNormalBroadcast(action, data, null);
    }

    /**
     * 发送普通全局广播（带权限）
     * @param action 广播动作
     * @param data 广播数据
     * @param permission 接收权限（可为null）
     */
    public void sendNormalBroadcast(String action, String data, String permission) {
        try {
            Intent intent = createIntent(action, data);
            
            if (permission != null) {
                context.sendBroadcast(intent, permission);
            } else {
                context.sendBroadcast(intent);
            }
            Log.d(TAG, "发送普通全局广播: " + action + (permission != null ? " (带权限)" : ""));
        } catch (Exception e) {
            Log.e(TAG, "发送普通全局广播失败: " + e.getMessage());
        }
    }

    /**
     * 发送有序全局广播
     */
    public void sendOrderedBroadcast(String action, String data, BroadcastReceiver resultReceiver) {
        sendOrderedBroadcast(action, data, null, resultReceiver, null, 0, null, null);
    }

    /**
     * 发送有序全局广播（完整版本）
     */
    public void sendOrderedBroadcast(String action, String data, String permission, 
                                    BroadcastReceiver resultReceiver, android.os.Handler scheduler, 
                                    int initialCode, String initialData, Bundle initialExtras) {
        try {
            Intent intent = createIntent(action, data);
            context.sendOrderedBroadcast(intent, permission, resultReceiver, scheduler, 
                    initialCode, initialData, initialExtras);
            Log.d(TAG, "发送有序全局广播: " + action);
        } catch (Exception e) {
            Log.e(TAG, "发送有序全局广播失败: " + e.getMessage());
        }
    }

    /**
     * 发送本地广播（推荐优先使用）
     */
    public void sendLocalBroadcast(String action, String data) {
        try {
            Intent intent = createIntent(action, data);
            localBroadcastManager.sendBroadcast(intent);
            Log.d(TAG, "发送本地广播: " + action);
        } catch (Exception e) {
            Log.e(TAG, "发送本地广播失败: " + e.getMessage());
        }
    }

    /**
     * 发送本地同步广播（相当于有序广播）
     */
    public void sendOrderedLocalBroadcast(String action, String data) {
        try {
            Intent intent = createIntent(action, data);
            localBroadcastManager.sendBroadcastSync(intent);
            Log.d(TAG, "发送本地有序广播: " + action);
        } catch (Exception e) {
            Log.e(TAG, "发送本地有序广播失败: " + e.getMessage());
        }
    }

    /**
     * 动态注册全局广播接收器
     */
    public boolean registerGlobalReceiver(BroadcastReceiver receiver, String action, int priority) {
        return registerGlobalReceiver(receiver, new String[]{action}, priority);
    }

    /**
     * 动态注册全局广播接收器（多Action）
     */
    public boolean registerGlobalReceiver(BroadcastReceiver receiver, String[] actions, int priority) {
        try {
            // 检查是否已注册
            if (isReceiverRegistered(receiver)) {
                Log.w(TAG, "接收器已注册，跳过: " + receiver.getClass().getSimpleName());
                return false;
            }

            IntentFilter filter = createIntentFilter(actions, priority);
            context.registerReceiver(receiver, filter);
            registeredReceivers.put(receiver, new RegisteredReceiverInfo(true, actions));
            Log.d(TAG, "注册全局广播接收器: " + receiver.getClass().getSimpleName());
            return true;
        } catch (Exception e) {
            Log.e(TAG, "注册全局广播接收器失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 动态注册本地广播接收器（推荐优先使用）
     */
    public boolean registerLocalReceiver(BroadcastReceiver receiver, String action) {
        return registerLocalReceiver(receiver, new String[]{action});
    }

    /**
     * 动态注册本地广播接收器（多Action）
     */
    public boolean registerLocalReceiver(BroadcastReceiver receiver, String[] actions) {
        try {
            // 检查是否已注册
            if (isReceiverRegistered(receiver)) {
                Log.w(TAG, "接收器已注册，跳过: " + receiver.getClass().getSimpleName());
                return false;
            }

            IntentFilter filter = createIntentFilter(actions, 0);
            localBroadcastManager.registerReceiver(receiver, filter);
            registeredReceivers.put(receiver, new RegisteredReceiverInfo(false, actions));
            Log.d(TAG, "注册本地广播接收器: " + receiver.getClass().getSimpleName());
            return true;
        } catch (Exception e) {
            Log.e(TAG, "注册本地广播接收器失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 注销单个广播接收器
     */
    public boolean unregisterReceiver(BroadcastReceiver receiver) {
        if (receiver == null) {
            Log.w(TAG, "接收器为null，无法注销");
            return false;
        }

        RegisteredReceiverInfo info = registeredReceivers.remove(receiver);
        if (info != null) {
            try {
                if (info.isGlobal) {
                    context.unregisterReceiver(receiver);
                } else {
                    localBroadcastManager.unregisterReceiver(receiver);
                }
                Log.d(TAG, "注销广播接收器: " + receiver.getClass().getSimpleName());
                return true;
            } catch (IllegalArgumentException e) {
                Log.w(TAG, "接收器未注册，注销失败: " + receiver.getClass().getSimpleName());
                return false;
            }
        }
        return false;
    }

    /**
     * 注销所有已注册的广播接收器
     * 重要：动态注册的广播接收器必须在适当的时候注销，避免内存泄漏
     */
    public void unregisterAllReceivers() {
        List<BroadcastReceiver> receiversToUnregister = new ArrayList<>(registeredReceivers.keySet());
        for (BroadcastReceiver receiver : receiversToUnregister) {
            unregisterReceiver(receiver);
        }
        registeredReceivers.clear();
        Log.d(TAG, "已注销所有广播接收器");
    }

    /**
     * 检查接收器是否已注册
     */
    public boolean isReceiverRegistered(BroadcastReceiver receiver) {
        return receiver != null && registeredReceivers.containsKey(receiver);
    }

    /**
     * 创建Intent对象
     */
    private Intent createIntent(String action, String data) {
        Intent intent = new Intent(action);
        if (data != null) {
            intent.putExtra("data", data);
        }
        // Android 8.0+ 发送隐式广播需要设置包名
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent.setPackage(context.getPackageName());
        }
        return intent;
    }

    /**
     * 创建IntentFilter对象
     */
    private IntentFilter createIntentFilter(String[] actions, int priority) {
        IntentFilter filter = new IntentFilter();
        for (String action : actions) {
            filter.addAction(action);
        }
        if (priority != 0) {
            filter.setPriority(priority);
        }
        return filter;
    }

    /**
     * 内部类：保存已注册的接收器信息
     */
    private static class RegisteredReceiverInfo {
        final boolean isGlobal;
        final String[] actions;

        RegisteredReceiverInfo(boolean isGlobal, String[] actions) {
            this.isGlobal = isGlobal;
            this.actions = actions;
        }
    }
}